Categories
JavaScript Tips

Useful JavaScript Tips — Variables and Arrays

Spread the love

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Assignment Operators

We can use compound assignment operators to make updating the values of numeric variables easier.

There are the += , -= , *= , /= , and %= operators which we can use to update numeric variables to whatever value we want based on the current one.

For instance, we can write:

x += 2;

Then we update the value of x by incrementing the current value by 2.

It’s the same as:

x = x + 2;

Likewise, we can do the same with the rest.

-= is subtraction.

*= is multiplication.

/= is for division.

And %= is for getting the remainder based on the current value.

So:

x %= 2;

is the same as:

x = x % 2;

Then we get the remainder of x divided by 2 based on the current value of x and reassigns it.

Converting Truthy or Falsy Values to Boolean

We can use the !! operator to convert anything to a boolean.

For instance, we can write:

!!""
!!0
!!null
!!undefined
!!NaN

They’re all falsy, so they all return false .

Other operands will return true . For instance, if we have:

!!"hi"

then that would return true .

Currying

Curry is the action of converting a function that takes multiple arguments into a series of functions that take a single argument.

It’s useful for creating functions that have some arguments applied and reuse that.

For instance, if we have an add function:

const add = (x, y) => {
  return x + y;
}

Then we can curry the function by writing:

const curriedAdd = (x) => {
  return (y) => {
    return x + y;
  }
}

Then we can call it by writing:

curriedAdd(1)(2)

and get 3.

Partial Application

We can partially apply arguments into a function by writing:

const plus10 = (y) => {
  return 10 + y;
}

Then we can write:

plus10(3);

Then we get 13.

To generalize this, we can write:

const partApply = (f, x) => {
  return (y) => {
    return f(x, y);
  }
}

Then we can call partApply by passing in a function for f and a value for x .

For instance, we can write:

const plus10 = partApply(add, 10);

Then we get 13 if we call plus10(3) since 10 is applied as the first argument.

Filtering and Sorting a List of Strings

We can sort filter strings with the filter method.

We can get the ones that we return an array that has words that have the same length as its index by writing:

const filtered = words
  .filter((word, index) => {
    return word.length > 2
  })

So if we have:

const words = ['do', 'if', 'foo', 'bar'];

Then we get:

["foo", "bar"]

Then we can call sort without any callback to sort strings since that’s how sort sorts array items without a callback.

So we can chain them by writing:

const filtered = words
  .filter((word, index) => {
    return word.length > 2
  })
  .sort();

Then we get [“bar”, “foo”] for filtered .

Using Immediately Invoked Function Expressions (IIFEs)

We can create and use IIFEs to enclose variables in a function so that they stay private.

For instance, we can write:

(() => {
  let x = 1;
  //...
})()

Then x stays inside the function.

This is one way to create private variables in a function.

Quick Way to Convert Numbers

To convert numbers easily, we can use the + operator to convert anything to a number.

For instance, we can write:

const one = +'1';

Then one is the number 1 instead of string '1' since we used the + operator on it.

Shuffle an Array

We can shuffle an array by using the sort method and return a random number that can be positive or negative so that we can shuffle them.

For instance, we can write:

const arr = [1, 2, 3];
arr.sort(() => -1 + (Math.random() * 2));

sort sorts an array in place, so we get a different value of it.

Returning -1 + (Math.random() * 2) will make the callback return something -1 and 1.

Conclusion

We can use various methods to filter and sort arrays.

Also, we can use assignment operators to make assignment statements shorter.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *